#!/usr/bin/env python3.9
# -*- encoding: utf-8 -*-
"""
@文件        :token.py
@说明        :jwt获取token和登录处理
@时间        :2022/11/29 11:29:48
@作者        :Mars
@版本        :1.0
"""

from rest_framework_simplejwt.authentication import JWTAuthentication
from rest_framework_simplejwt.tokens import RefreshToken

from mars.utils.exceptions.enums import StatusCodeEnum
from mars.utils.exceptions.exceptions import APIException


class JwtAuthentication(JWTAuthentication):
    def authenticate(self, request):
        res = super().authenticate(request)
        if not res:
            raise APIException(StatusCodeEnum.TOKEN_ERR)
        user = res[0]
        #
        user.openid = user.oauthmpuser_set.first().openid

        return (user, res[1])
 


class Token:
    @staticmethod
    def get_token(payload):
        refresh = RefreshToken.for_user(payload)
        return {
            "refresh": str(refresh),
            "access": str(refresh.access_token),
        }
